<template>
  <el-form ref="seriesFormRef" :model="spuData" :rules="rules" label-width="80px" :inline="true" size="mini" class="series">
    <!-- 头部 -->
    <div class="series-header">
      <el-form-item label="SPU名称" :prop="increased ? 'spuName' : 'chgSpuName'">
        <el-input
          v-model.trim="spuData[increased ? 'spuName' : 'chgSpuName']"
          placeholder="请输入SPU名称"
          maxlength="45"
          :disabled="isDisabled"
          show-word-limit
          @input="changStatus"
        />
      </el-form-item>
      <el-form-item label="SPU备注" prop="remark">
        <el-input v-model="spuData.remark" placeholder="请输入SPU备注" maxlength="255" :disabled="isDisabled" show-word-limit @input="changStatus" />
      </el-form-item>
      <el-form-item v-if="!isDisabled" label=" " class="sava-btn">
        <el-button size="mini" type="primary" round @click="sava">
          {{ isChange || !listDisplay.attribute ? '保存' : '下一步' }}
        </el-button>
      </el-form-item>
    </div>

    <div class="ess-table">
      <ess-table :pagination-show="false" :count-height="false" size="mini" :thead-list="theadList" :data-list="spuData.skuInfoList">
        <div v-if="!isDisabled" slot="right" class="menu">
          <el-button size="mini" round @click="addSku">新增SKU</el-button>
        </div>

        <template v-slot:mainProduct="{ scope }">
          <el-form-item prop="upc" class="main-radio">
            <input v-model="spuData.upc" class="main-product-radio" type="radio" :value="scope.row.upcNbr" :disabled="isDisabled" @input="changStatus" />
          </el-form-item>
        </template>

        <template v-slot:mainAttrValueAlias="{ scope, parameter }">
          <el-form-item class="table-input" :prop="`skuInfoList[${scope.$index}]`" :rules="[{ validator: mainAttrRules, trigger: 'blur' }]">
            <el-input v-model.trim="scope.row[parameter.value]" :placeholder="`请输入${parameter.label}`" :disabled="isDisabled" @input="changStatus" />
          </el-form-item>
        </template>

        <template v-slot:secondAttrValueAlias="{ scope, parameter }">
          <el-form-item class="table-input" :prop="`skuInfoList[${scope.$index}]`" :rules="[{ validator: secondAttrRules, trigger: 'blur' }]">
            <el-input v-model.trim="scope.row[parameter.value]" :placeholder="`请输入${parameter.label}`" :disabled="isDisabled" @input="changStatus" />
          </el-form-item>
        </template>

        <template v-slot:operation="{ scope }">
          <el-button type="text" icon="el-icon-delete" :disabled="isDisabled || spuData.skuInfoList.length < 2" @click="deleteUpc(scope)" />
        </template>
      </ess-table>
    </div>

    <add-upc
      ref="addUpcRef"
      :increased="increased"
      :is-add-upc="true"
      :sku-info-list="spuData.skuInfoList"
      :spu-id="spuData[increased ? 'spuId' : 'chgSpuId']"
      @addSuccess="addSuccess"
    />
  </el-form>
</template>
<script>
import { deleteSpuSkuMapping, setSpuSeriesInfo } from '@/api/coi/onlineTaskAPI/spu.js'
import { deleteChgSpuSkuMapping, setChgSpuSeriesInfo } from '@/api/coi/onlineTaskAPI/spuEdit.js'
import essTable from '@/components/eTable/eTable.vue'
import addUpc from './addSPU.vue'

export default {
  name: 'Series',
  components: {
    essTable,
    addUpc
  },
  props: {
    spuData: {
      type: Object,
      required: true
    },
    isDisabled: {
      type: Boolean,
      default: true
    },
    listDisplay: {
      type: Object,
      required: true
    },
    increased: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      rules: {
        spuName: [
          { required: true, message: '请输入SPU名称', trigger: 'blur' },
          { max: 45, message: 'SPU名字在45个字符之内', trigger: 'blur' }
        ],
        remark: [{ max: 255, message: '备注在255个字符之内', trigger: 'blur' }],
        upc: [{ required: true, message: ' ', trigger: 'blur' }]
      },
      tableData: [],
      isChange: false
    }
  },
  computed: {
    theadList: {
      get() {
        const arrList = []
        const isMain = []
        const { mainAttrName, secondaryAttrName } = this.spuData
        if (mainAttrName) {
          arrList.push({
            name: `* ${mainAttrName}`,
            label: `${mainAttrName}`,
            minWidth: '100',
            slot: 'mainAttrValueAlias',
            value: 'mainAttrValueAlias'
          })
        }
        if (secondaryAttrName) {
          arrList.push({
            name: `${secondaryAttrName}`,
            label: `${secondaryAttrName}`,
            minWidth: '100',
            slot: 'secondAttrValueAlias',
            value: 'secondAttrValueAlias'
          })
        }
        if (this.increased) {
          isMain.push({
            name: '*主品',
            width: '80',
            slot: 'mainProduct'
          })
        }
        return [
          ...isMain,
          {
            name: 'UPC(不含检验码)',
            value: 'upcWoCd',
            minWidth: '100'
          },
          {
            name: '商品名称',
            value: 'upcName',
            minWidth: '100'
          },
          ...arrList,
          {
            name: '操作',
            width: '100',
            slot: 'operation'
          }
        ]
      },
      deep: true
    },
    secondAttrIsRequired() {
      return this.spuData.skuInfoList.some((_) => _.secondAttrValueAlias)
    },
    mainAttrRules() {
      const fun = (rule, value, callback) => {
        if (!value.mainAttrValueAlias) callback(new Error('主销售属性不能为空'))
        else if (this.secondAttrIsRequired) {
          const arr = this.filterAtt(value)
          if (arr.length > 1) callback(new Error('销售属性组合重复'))
          else callback()
        } else callback()
      }
      return fun
    },
    secondAttrRules() {
      const fun = (rule, value, callback) => {
        if (!value.secondAttrValueAlias && this.secondAttrIsRequired) callback(new Error('销售属性为空'))
        else if (this.secondAttrIsRequired) {
          const arr = this.filterAtt(value)
          if (arr.length > 1) callback(new Error('销售属性组合重复'))
          else callback()
        } else callback()
      }
      return fun
    }
  },
  methods: {
    checkFormData() {
      let result = null
      this.$refs.seriesFormRef.validate((v) => {
        result = v
      })
      if (!this.spuData.upc && this.increased) result = false
      return result
    },
    changStatus() {
      this.isChange = true
    },
    filterAtt(value) {
      return this.spuData.skuInfoList.filter(
        (_) =>
          _.mainAttrValueAlias &&
          _.secondAttrValueAlias &&
          _.mainAttrValueAlias + _.secondAttrValueAlias === value.mainAttrValueAlias + value.secondAttrValueAlias
      )
    },
    addSku() {
      this.$refs.addUpcRef.dialogVisible = true
    },
    addSuccess(item) {
      this.spuData.skuInfoList.push(item)
      this.changStatus()
    },
    deleteUpc({ row }) {
      console.log(this.$parent)
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteUpcRequest({ upc: row.upcNbr })
        })
        .catch(() => {})
    },
    async deleteUpcRequest(params) {
      try {
        this.$emit('changeLoading', true)
        const requestFun = this.increased ? deleteSpuSkuMapping : deleteChgSpuSkuMapping
        const { result } = await requestFun(params)
        if (!result) return
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        const index = this.spuData.skuInfoList.findIndex((_) => _.upcNbr === params.upc)
        if (index !== -1) this.spuData.skuInfoList.splice(index, 1)
        this.changStatus()
      } finally {
        this.$emit('changeLoading', false)
      }
    },
    sava() {
      if (!this.spuData.upc && this.increased) {
        this.$message({
          type: 'error',
          message: '请选择一个主品'
        })
        return
      }
      this.$refs.seriesFormRef.validate((v) => {
        console.log(v)
        if (!v) return
        this.savaRequery()
      })
    },
    async savaRequery() {
      console.log(this.isChange)
      if (!this.isChange) return this.$emit('changeTag', 'attribute')
      this.$emit('changeLoading', true)
      const { mainAttrName, remark, secondaryAttrName, skuInfoList, upc } = this.spuData
      try {
        const requestFun = this.increased ? setSpuSeriesInfo : setChgSpuSeriesInfo
        const result = await requestFun({
          mainAttrName,
          remark,
          secondaryAttrName,
          skuInfoList,
          [this.increased ? 'spuId' : 'chgSpuId']: this.spuData[this.increased ? 'spuId' : 'chgSpuId'],
          [this.increased ? 'spuName' : 'chgSpuName']: this.spuData[this.increased ? 'spuName' : 'chgSpuName'],
          upc
        })
        if (result.code !== '0') return
        this.$message({
          type: 'success',
          message: '保存成功'
        })
        this.changStatus(false)
        this.$emit('refresh', 'attribute')
      } finally {
        this.$emit('changeLoading', false)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.series {
  .series-header {
    position: relative;
    .sava-btn {
      position: absolute;
      right: 0;
    }
  }
  .ess-table {
    .menu {
      padding-bottom: 8px;
    }
    .main-radio {
      margin: 0;
    }
    .table-input {
      margin: 0;
      margin-bottom: 18px;
    }
  }
}
/deep/ .el-icon-delete {
  font-size: 16px;
}
.main-product-radio {
  cursor: pointer;
}
</style>
